package com.jml.zlhq.app.ui;

import java.util.HashMap;
import java.util.Map;

import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

import com.jml.zlhq.app.R;
import com.jml.zlhq.app.URLs;
import com.jml.zlhq.app.service.HttpService;
import com.jml.zlhq.app.ui.LoginActivity.CheckBind;
import com.jml.zlhq.app.util.BaseTools;
import com.jml.zlhq.app.util.StringUtil;
import com.jml.zlhq.app.util.UIUtil;
import com.jml.zlhq.app.widgets.CommonDialog;
import com.loopj.android.http.TextHttpResponseHandler;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

public class BindPhoneActivity extends BaseActivity {
	private EditText vcode,phonee;
	private TextView msg;
	@SuppressWarnings("unused")
	private String vcodeStr;
	private Button gvcode,submit;
	private String phone;
	private boolean getvd = false;
	private int time60 = 60;
	@SuppressLint("HandlerLeak") 
	private Handler mHandler = new Handler(){
		@Override
		public void dispatchMessage(Message msg) {
			if(time60>0){
				gvcode.setText(time60+" 秒后重新发送");
				time60--;
				sendEmptyMessageDelayed(1, 1000);
			}else{
				gvcode.setText("重新获取验证码");
			}
		}
	};
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.bindphone_activity);
		
		LinearLayout leftLay = (LinearLayout) findViewById(R.id.content_header_left_lay);
		LinearLayout rightLay = (LinearLayout) findViewById(R.id.content_header_right_lay);
		leftLay.setOnClickListener(this);
		rightLay.setOnClickListener(this);
		AutoCompleteTextView centerEdit = (AutoCompleteTextView) findViewById(R.id.content_header_center_edit);
		centerEdit.setVisibility(View.GONE);
		ImageView leftImage = (ImageView) findViewById(R.id.content_header_left_img);
		leftImage.setImageResource(R.drawable.back_selector);
		ImageView roghtImage1 = (ImageView) findViewById(R.id.content_header_right_img);
		roghtImage1.setVisibility(View.INVISIBLE);
		TextView centerText = (TextView) findViewById(R.id.content_header_center_text);
		centerText.setText("绑定手机号");
		TextView rightText = (TextView) findViewById(R.id.content_header_right_text);
		rightText.setVisibility(View.INVISIBLE);
		TextView cityChosed = (TextView) findViewById(R.id.content_header_center_text2);
		cityChosed.setVisibility(View.GONE);
		
		vcode = (EditText) findViewById(R.id.bind_vcode);
		phonee = (EditText) findViewById(R.id.bind_phone);
		msg = (TextView) findViewById(R.id.bind_msg);
		gvcode = (Button) findViewById(R.id.bind_revcode);
		submit = (Button) findViewById(R.id.bind_submit);
		try {
			Bundle data = getIntent().getExtras();
			phone = data.getString("phone");
			//phoneinfo.setText(Html.fromHtml("验证码已通过短信形式发送到：<font color='#f3f3f3'>"+phone+"</font>"));
		} catch (Exception e) {
		}
		
		//mHandler.sendEmptyMessage(1);
		gvcode.setOnClickListener(this);
		submit.setOnClickListener(this);
		
		//loadData(null);
		
		phonee.setOnFocusChangeListener(new OnFocusChangeListener() {
			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				Drawable drawable1 = getResources().getDrawable(hasFocus?R.drawable.loginico_phone_hover:R.drawable.loginico_phone);
				drawable1.setBounds(0, 0, drawable1.getMinimumWidth(), drawable1.getMinimumHeight()); 
				((EditText)v).setCompoundDrawables(drawable1, null, null, null);
			}
		});
		vcode.setOnFocusChangeListener(new OnFocusChangeListener() {
			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				Drawable drawable1 = getResources().getDrawable(hasFocus?R.drawable.loginico_code_hover:R.drawable.loginico_code);
				drawable1.setBounds(0, 0, drawable1.getMinimumWidth(), drawable1.getMinimumHeight()); 
				((EditText)v).setCompoundDrawables(drawable1, null, null, null);
			}
		});
	}

	@Override
	public void loadData(Map<String, String> param) {
		if(getvd){
			return;
		}
		getvd = true;
		mHandler.sendEmptyMessage(1);
		Map<String, String> map = new HashMap<String, String>();
		map.put("phone", phone);
		map.put("auth_token", appContext.getLoginUid());
		HttpService.postByText(URLs.USER_BIND_VCODE, map, new TextHttpResponseHandler() {
			
			@Override
			public void onSuccess(int arg0, Header[] arg1, String result) {
				getvd = false;
				try {
					JSONObject json = new JSONObject(result);
					Log.i("==vcode==", result);
					if(BaseTools.getFrom("status", json).equals("0")){
						vcodeStr = BaseTools.getFrom("data", json);
					}else{
						msg.setText(BaseTools.getFrom("message", json));
					}
				} catch (JSONException e) {
					e.printStackTrace();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			
			@Override
			public void onFailure(int arg0, Header[] arg1, String arg2, Throwable arg3) {
				getvd = false;
				msg.setText("访问错误");
			}
		});
	}

	@Override
	public void clearData() {}
	
	@Override
	public void finish() {
//		String phonen = BaseTools.getFrom("phone", appContext.getLoginUser());
//		if(StringUtil.isEmpty(phonen)||"null".equals(phonen)){
//			final CommonDialog show = new CommonDialog(activity, true);
//			show.show(true, true, true, "提示", "取消绑定手机号将推出登录", "继续绑定", "退出登录", new OnClickListener(){
//				@Override
//				public void onClick(View v) {
//					show.dismiss();
//				}
//			}, new OnClickListener(){
//				@Override
//				public void onClick(View v) {
//					appContext.Logout(BindPhoneActivity.class.getName());
//					LoginActivity.afterLogined(activity,new CheckBind() {
//						@Override
//						public void checkBind(String phone) {
//							//TODO
//						}
//					});
//					show.dismiss();
//					BindPhoneActivity.super.finish();
//				}
//			});
//		}else{
//			super.finish();
//		}
		super.finish();
	}

	@Override
	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.content_header_left_lay:
			finish();
			break;
		case R.id.bind_revcode:
			phone = phonee.getText().toString();
			if(StringUtil.isEmpty(phone)||!StringUtil.isPhone(phone)){
				msg.setText("账号非手机号");
				return;
			}
			if(time60==0||time60==60){
				time60 = 60;
				loadData(null);
			}
			break;
		case R.id.bind_submit:
			String vcodeStrTmp = vcode.getText().toString();
			if(StringUtil.isEmpty(vcodeStrTmp)){
				msg.setText("验证码不正确");
				return;
			}
			
			Map<String, String> smap = new HashMap<String, String>();
			smap.put("bindphone", phone.trim());
			smap.put("code", vcodeStrTmp.trim());
			smap.put("auth_token", appContext.getLoginUid());
			final Dialog  mProDialog =  UIUtil.showLoadingDialog(activity, "保存中，请稍后...", false);
			HttpService.postByText(URLs.USER_BING_PHONE, smap, new TextHttpResponseHandler() {
				
				@Override
				public void onSuccess(int arg0, Header[] arg1, String result) {
					mProDialog.dismiss();
					try {
						JSONObject json = new JSONObject(result);
						Log.i("==vcode==", result);
						if(BaseTools.getFrom("status", json).equals("0")){
							JSONObject user = appContext.getLoginUser();
							user.put("phone", phone.trim());
							appContext.Login(user.toString());
							//LoginActivity.login(smap.get("phonenumber"),smap.get("password"), activity);
							finish();
						}else{
							msg.setText(BaseTools.getFrom("message", json));
						}
					} catch (JSONException e) {
						e.printStackTrace();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
				
				@Override
				public void onFailure(int arg0, Header[] arg1, String arg2, Throwable arg3) {
					mProDialog.dismiss();
					msg.setText("访问错误");
				}
			});
			break;
		default:
			break;
		}
	}

}
